#include "locallistwidget.h"
#include "ui_locallistwidget.h"
#include "localfolderdialog.h"
#include <QDebug>
#include <QTimer>

LocalListWidget::LocalListWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LocalListWidget)
{
    ui->setupUi(this);

    QVBoxLayout *containerLayout = static_cast<QVBoxLayout*>(ui->container->layout());
    containerLayout->setAlignment(Qt::AlignTop);       // 布局内所有子控件顶对齐
    containerLayout->setContentsMargins(60, 0, 57, 0);    // 左边距60, 右边距 60-3

    // ban掉可能出现的横向滑动条
    ui->scrollArea->setWidgetResizable(true);
    ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 永久关掉横向
    ui->scrollArea->viewport()->installEventFilter(this); // 添加事件过滤器来处理滚动区域大小变化

    QString htmlText = "<span style='font-family:Microsoft YaHei; font-size:33px; font-weight:bold; color: rgb(40, 50, 72);'>本地音乐</span>  "
                       "<span style='font-family:Microsoft YaHei; font-size:18px; font-weight:300 ; color:#9ca3af;'>共 " + QString::number(_songItems.size()) +" 首</span>";
    ui->label_listName->setText(htmlText);
    ui->label_listName->setTextFormat(Qt::RichText);  // 确保是富文本模式

//    _selectedPaths << "D:/CloudMusic";
}

LocalListWidget::~LocalListWidget()
{
    delete ui;
}

void LocalListWidget::flush()
{
    ui->pushButton_download->clicked();
}

#include <QResizeEvent>
// 添加事件过滤器函数以处理大小变化
bool LocalListWidget::eventFilter(QObject *watched, QEvent *event)
{
    if (!ui->scrollArea || !ui->scrollArea->viewport()) {
        qDebug() << "Scroll area or viewport is null!";
        return false;
    }
    if (watched == ui->scrollArea->viewport() && event->type() == QEvent::Resize) {
        // 当窗口大小变化时调整container的最小宽度
        QResizeEvent *resizeEvent = (QResizeEvent*)(event);
        int newWidth = resizeEvent->size().width();
        ui->container->setMinimumWidth(newWidth);
    }

    return QWidget::eventFilter(watched, event);
}


void LocalListWidget::addSongItem(SongItemWidget *songItem)
{
    _songItems.push_back(songItem);
    songItem->setIndex(_songItems.size());
    connect(songItem, &SongItemWidget::played, this, &LocalListWidget::on_songItem_played);
    songItem->connectManager(); 
    ui->container->layout()->addWidget(songItem);
}

void LocalListWidget::on_songItem_played(int index, bool play)
{
    emit played(_songItems[index]->songItem(), play);
}

void LocalListWidget::on_pushButton_playAll_clicked()
{
    QVector<QUrl> songs;
    for(auto& e : _songItems){
        songs.push_back(e->songItem().url());
    }
    emit playAll(songs);
}

void LocalListWidget::on_pushButton_clicked()
{
    LocalFolderDialog dialog(this);
    dialog.initPaths(_selectedPaths);
    if(dialog.exec() == QDialog::Accepted){
        _selectedPaths = dialog.getPaths();
        ui->pushButton_download->clicked();
    }
    qDebug() << "选择的文件夹为:";
    for(auto& path : _selectedPaths){
        qDebug() << path;
    }
    qDebug() << "-------------";
}

#include <QMimeDatabase>
#include <QMimeType>
bool isMedia(const QString& path){
    QMimeDatabase db;
    QMimeType type = db.mimeTypeForFile(path);
    return type.name().startsWith("audio/");
}

#include <QDir>
#include <QMediaPlayer>
#include <QMimeData>
#include <QMediaMetaData>
#include "songitem.h"
#include "songmanager.h"
void LocalListWidget::on_pushButton_download_clicked()
{
    for(int i = 0; i < _songItems.size(); i++){
        ui->container->layout()->removeWidget(_songItems[i]);
        delete _songItems[i];
    }
    _songItems.clear();

    qDebug() << "刷新:";
    QVector<QDir> dirs(_selectedPaths.begin(), _selectedPaths.end());
    for(auto& dir : dirs){
        QStringList paths = dir.entryList();
        for(auto& path : paths){
            qDebug() << path;
            if (isMedia(path)){
                path = dir.absoluteFilePath(path);
                qDebug() << "找到音频文件 : " << path;
                SongItem song;
                song.local_url = QUrl::fromLocalFile(path);
                qDebug() << "song.local_url : " << song.local_url;
                if (SongManager::instance()->getSongItem(&song)){
                } else {
                    QMediaPlayer player(this);
                    player.setMedia(song.local_url);

                    while(!player.isMetaDataAvailable())
                    {
                        QCoreApplication::processEvents();
                    }
//                    QStringList keys = player.availableMetaData();
//                    for (const QString &key : keys) {
//                        qDebug() << key << ":" << player.metaData(key);
//                    }
                    song.duration = player.duration();
//                    if(song.duration == 0) continue;
                    QStringList artists = player.metaData(QMediaMetaData::Author).toStringList();
                    song.name = player.metaData(QMediaMetaData::Title).toString();
                    song.album = player.metaData(QMediaMetaData::AlbumTitle).toString();
                    for(int i = 0; i < artists.size(); i++) {
                        if(i) song.artist += " / ";
                        song.artist += artists[i];
                    }
                    QImage thumbnailImage = player.metaData(QMediaMetaData::ThumbnailImage).value<QImage>();
                    if (!thumbnailImage.isNull()) {
                        song.image = QPixmap::fromImage(thumbnailImage);
                    } else {
                        QByteArray imageData = player.metaData(QMediaMetaData::CoverArtImage).toByteArray();
                        if (!imageData.isEmpty()) {
                            song.image.loadFromData(imageData);
                        } else {
                            qDebug() << "No cover art available";
                        }
                    }
                    SongManager::instance()->addSongItem(song);
                }
                SongItemWidget* songIW = new SongItemWidget(this);
                songIW->setImageSize(0);
                songIW->setSongItem(song);
                QTimer::singleShot(0, this, [=]{addSongItem(songIW); });
            }
        }
    }

    QString htmlText = "<span style='font-family:Microsoft YaHei; font-size:33px; font-weight:bold; color: rgb(40, 50, 72);'>本地音乐</span>  "
                       "<span style='font-family:Microsoft YaHei; font-size:18px; font-weight:300 ; color:#9ca3af;'>共 " + QString::number(_songItems.size()) +" 首</span>";
    ui->label_listName->setText(htmlText);
    ui->label_listName->setTextFormat(Qt::RichText);  // 确保是富文本模式
}
